package com.zis.platform.core.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zis.common.SearchParams;
import com.zis.platform.common.service.impl.BaseServiceImpl;
import com.zis.platform.core.dao.ResRoleDao;
import com.zis.platform.core.dao.RoleDao;
import com.zis.platform.core.entity.ResEntity;
import com.zis.platform.core.entity.ResRoleEntity;
import com.zis.platform.core.entity.RoleEntity;
import com.zis.platform.core.service.RoleService;

@Service
public class RoleServiceImpl extends BaseServiceImpl<RoleEntity> implements RoleService
{
    
    @Autowired
    RoleDao roleDao;
    
    @Autowired
    ResRoleDao resRoleDao;
    
    @Override
    public List<RoleEntity> findByCondition(SearchParams params)
        throws Exception
    {
        return this.roleDao.findByCondition(params);
    }
    
    @Override
    public List<RoleEntity> findAll()
        throws Exception
    {
        return this.roleDao.findAll();
    }
    
    @Override
    public RoleEntity saveOrUpdate(RoleEntity role)
    {
        if (role != null)
        {
            if (StringUtils.isBlank(role.getRoleId()))
            {
                role.setRoleId(UUID.randomUUID().toString());
                int insertNum = roleDao.insertSelective(role);
                if (insertNum > 0)
                {
                    return role;
                }
            }
            else
            {
                int updateNum = roleDao.updateByPrimaryKeySelective(role);
                if (updateNum > 0)
                {
                    return role;
                }
            }
        }
        return null;
    }
    
    @Override
    public int deleteByRoleIds(String[] roleIds)
    {
        return this.roleDao.deleteByRoleIds(roleIds);
    }
    
    @Override
    public int saveResSetting(RoleEntity role)
        throws Exception
    {
        // 删除旧数据
        resRoleDao.deleteByRoleId(role.getRoleId());
        List<ResRoleEntity> list = new ArrayList();
        // 保存新数据
        if (role.getResList() != null && role.getResList().size() > 0)
        {
            for (ResEntity res : role.getResList())
            {
                ResRoleEntity resRole = new ResRoleEntity();
                resRole.setRrId(UUID.randomUUID().toString());
                resRole.setRoleId(role.getRoleId());
                resRole.setResId(res.getResId());
                list.add(resRole);
            }
            return this.resRoleDao.batchSave(list);
        }
        return 1;
    }
    
    @Override
    public RoleEntity findRoleAndResByRoleId(String roleId)
    {
        return this.roleDao.findRoleAndResByRoleId(roleId);
    }
    
}
